function detmag = bvqxfile_detectmagic(filename, mag)
% BVQXfile::<PRIVATE>::detectmagic  - detect filetype from magic token
%
% THIS FUNCTION IS AN INTERNAL FUNCTION OF THE CLASS
%
% @BVQXfile
%
% AND IT SHOULD NEVER BE CALLED FROM OUTSIDE THE CLASS CODE

% Version:  v0.7b
% Build:    7082923
% Date:     Aug-29 2007, 11:20 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% default: no magic
detmag = '';

% read file first
try
    fileinfo = dir(filename);
    if numel(fileinfo) ~= 1 || ...
        fileinfo.isdir
        return;
    end
    filesize = fileinfo.bytes;
    filecont = transio(filename, 'ieee-le', 'uint8', 0, [1, filesize]);
catch
    return;
end

% try magics
for ftc = 1:numel(mag)

    % get name, range, type, token, and infer detected type
    mmag = mag(ftc);
    mname  = lower(mmag.name);
    mnames = find(mname == '_');
    if isempty(mnames) || ...
        mnames(1) < 4
        warning(...
            'BVQXfile:InvalidToken', ...
            'Invalid Magic token tag: %s.', ...
            mname ...
        );
        continue;
    end
    mrange = mmag.range;
    mtype  = lower(mmag.type);
    mtoken = mmag.magic;
    mdtype = mname(1:mnames(1)-1);
    if mrange(2) > filesize
        continue;
    end
    mdcont = char(filecont(1, mrange(1):mrange(2)));

    % default: no match
    mmatched = false;

    % what type
    switch (mtype)
        case {'hex'}
            if numel(mtoken) == numel(mdcont) && ...
                all(double(mtoken(:)') == double(mdcont(:)'))
                mmatched = true;
            end
        case {'regexp'}
            if ~isempty(regexp(char(mdcont), mtoken, 'once'))
                mmatched = true;
            end
        case {'regexpi'}
            if ~isempty(regexpi(char(mdcont), mtoken))
                mmatched = true;
            end
        case {'strfind'}
            if ~isempty(strfind(char(mdcont), mtoken))
                mmatched = true;
            end
    end

    % leave loop ?
    if mmatched
        detmag = mdtype;
        break;
    end

end
